<template>
  <div class="dept-page">
    <transition name="el-zoom-in-top">
      <el-form v-show="searchDeptVisible" inline size="mini" :model="searchDeptForm" ref="searchDeptForm" @keyup.enter.native="getDeptList">
        <el-form-item label="部门检索">
          <el-input v-model="searchDeptForm.word" clearable placeholder="请选择检索的部门名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchDeptForm.status" clearable placeholder="请选择检索的部门状态">
            <el-option label="可用" value="0"></el-option>
            <el-option label="不可用" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button :disabled="loading" @click="searchDeptHandle" type="primary"
                     icon="el-icon-search">查询</el-button>
          <el-button :disabled="loading" @click="resetSearchDeptHandle" plain
                     icon="el-icon-refresh-right">重置</el-button>
        </el-form-item>
      </el-form>
    </transition>

    <div class="d-tool">
      <el-button :disabled="loading" @click="openDeptDialogHandle(undefined, false)"
                 type="primary" size="mini" plain icon="el-icon-plus">添 加</el-button>

      <!-- 还差一个刷新表格事件 -->
      <right-tool-bar :search-visible="searchDeptVisible" :search-load="loading"
                      @toggle-search="searchDeptVisible = !searchDeptVisible"
                      @refresh-table="closeDeptDialogHandle(true)" />
    </div>

    <el-table
      highlight-current-row
      v-loading="dataLoad"
      element-loading-text="部门数据加载中"
      element-loading-spinner="el-icon-loading"
      :data="deptTableData"
      row-key="deptId"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      ref="deptTable"
    >
      <el-table-column prop="deptName" header-align="center" label="部门名称" show-overflow-tooltip></el-table-column>
      <el-table-column prop="sort" header-align="center" align="center" label="排序等级"></el-table-column>
      <el-table-column prop="status" header-align="center" align="center" label="状态">
        <template v-slot="scope">
          <el-tag :type="scope.row.status === 0 ? 'primary' : 'danger'">
            {{ scope.row.status === 0 ? '可用' : '不可用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" header-align="center" align="center" label="更新时间" width="135"></el-table-column>
      <el-table-column prop="updateUser" header-align="center" align="center" label="更新用户"></el-table-column>
      <el-table-column prop="createTime" header-align="center" align="center" label="创建时间" width="135"></el-table-column>
      <el-table-column prop="createUser" header-align="center" align="center" label="创建用户"></el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="150"
        label="操作">
        <template v-slot="scope">
          <el-button type="text" icon="el-icon-plus" size="small" @click="openDeptDialogHandle(scope.row, false)">添加</el-button>

          <el-dropdown :disabled="loading">
            <span class="el-dropdown-link dropdown-opt" :style="{ '--color': themeColor }">
              更多<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item icon="el-icon-user" @click.native="toDeptRolePageHandle(scope.row)">
                部门角色
              </el-dropdown-item>
              <el-dropdown-item icon="el-icon-user" @click.native="toDeptUserPageHandle(scope.row)">
                部门用户
              </el-dropdown-item>
              <el-dropdown-item v-show="scope.row.status === 1" icon="el-icon-check" divided
                                @click.native="updateDeptStatusHandle(scope.row, 0)">
                使用
              </el-dropdown-item>
              <el-dropdown-item v-show="scope.row.status === 0" icon="el-icon-close" divided
                                @click.native="updateDeptStatusHandle(scope.row, 1)">
                禁用
              </el-dropdown-item>
              <el-dropdown-item icon="el-icon-edit" @click.native="openDeptDialogHandle(scope.row, true)">
                修改
              </el-dropdown-item>
              <el-dropdown-item icon="el-icon-delete" @click.native="deleteDeptBeforeHandle(scope.row)">
                删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalNum"
      layout="total, sizes, prev, pager, next, jumper"
      class="paging">
    </el-pagination>

    <!-- 部门添加/修改弹出框-->
    <dept-save-update ref="optDeptDialog" @close-dialog="closeDeptDialogHandle" />

    <!-- 部门删除提示弹出框 -->
    <dept-delete-confirm ref="deptDeleteConfirmDialog" @close-dept-delete-dialog="closeDeptDeleteDialogHandle" />

  </div>
</template>

<script>
  import RightToolBar from '@/components/common/right-toolbar'
  import DeptSaveUpdate from "@/components/dept/save-update";
  import DeptDeleteConfirm from "@/components/dept/delete-confirm";

  export default {
    layout: 'admin',
    name: "admin-system-dept",
    components: { RightToolBar, DeptSaveUpdate, DeptDeleteConfirm },
    data () {
      return {
        // 部门数据列表
        deptList: [],
        // 部门表格数据列表
        deptTableData: [],
        // 记录上一次部门检索表单的数据
        requestParams: [ '', '' ],
        // 数据获取模式[0-请求接口 1-请求接口，然后本地缓存 2及以上-截取本地缓存数据]
        requestMode: 0,
        // 数据是否加载[false-不加载 true-加载]
        dataLoad: false,
        // 按钮是否可被点击[false-可以被点击 true-不可被点击]
        buttonLoad: false,
        // 部门检索表单是否显示
        searchDeptVisible: true,
        // 部门检索表单对象
        searchDeptForm: {
          // 部门名称
          word: '',
          // 部门状态
          status: '',
        },
        // 当前展示页码
        pageIndex: 1,
        // 当前页显示个数
        pageSize: 10,
        // 当前一级部门数量
        totalNum: 0
      }
    },
    computed: {
      // 主题颜色
      themeColor() {
        return this.$store.state.settings.theme
      },
      // 数据加载中
      loading() {
        return this.dataLoad || this.buttonLoad
      }
    },
    activated () {
      // this.getDeptList()
    },
    created() {
      if (process.client) {
        this.getDeptList()
      }
    },
    methods: {
      /**
       * 部门检索事件
       */
      searchDeptHandle() {
        this.pageIndex = 1
        this.getDeptList()
      },
      /**
       * 重置部门检索表单对象事件
       */
      resetSearchDeptHandle() {
        let searchDeptForm = this.searchDeptForm
        if (searchDeptForm.word === '' && searchDeptForm.status === '') {
          this.notify('info', "温馨提示", '所有查询条件为空')
          return
        }
        searchDeptForm.word = ''
        searchDeptForm.status = ''
        // 重新获取表格数据
        this.getDeptList()
      },
      /**
       * 获取部门数据列表方法
       */
      getDeptList() {
        let searchDeptForm = this.searchDeptForm
        let requestParams = this.requestParams
        if (searchDeptForm.word === '' && searchDeptForm.status === '') {
          // 请求参数为空
          requestParams[0] = ''
          requestParams[1] = ''
          this.requestMode = 0;
        } else {
          // 请求参数不为空
          if (searchDeptForm.word === requestParams[0] && searchDeptForm.status === requestParams[1]) {
            // 请求参数与上一次请求参数相同
            this.requestMode = Math.min(this.requestMode + 1, 5);
          } else {
            requestParams[0] = searchDeptForm.word
            requestParams[1] = searchDeptForm.status
            this.requestMode = 1
          }
        }
        if (this.requestMode > 1) {
          // 直接读取本地数据
          this.getCacheDeptList()
          return;
        }
        let formObj = {
          requestMode: this.requestMode,
          word: searchDeptForm.word,
          status: searchDeptForm.status,
          page: this.pageIndex,
          limit: this.pageSize
        }
        // console.log('请求参数对象', formObj, 'requestMode', this.requestMode)
        // 表格数据加载
        this.dataLoad = true
        this.$axios.$post('/sys/dept/page/list', formObj)
          .then(({ data:page }) => {
            this.deptList = page.list
            this.totalNum = page.totalNum

            if (this.requestMode === 0) {
              this.deptTableData = page.list
            } else {
              this.getCacheDeptList()
            }

          })
          .catch(() => {})
          .finally(() => {
            // 表格加载结束
            this.dataLoad = false
          })
      },
      /**
       *
       */
      getCacheDeptList() {
        let deptList = this.deptList
        // 不是请求接口获取数据
        let start = (this.pageIndex - 1) * this.pageSize,
            end = Math.min(start + this.pageSize, deptList.length);
        // 分页截取
        this.deptTableData = deptList.slice(start, end);
      },
      /**
       * 表格每页显示数量变化事件
       * @param val 最新值
       */
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDeptList()
      },
      /**
       * 表格页码切换事件
       * @param val 最新值
       */
      currentChangeHandle (val) {
        if (this.pageIndex === val) {
          return
        }
        this.pageIndex = val
        this.getDeptList()
      },
      /**
       * 更新部门状态事件
       * @param {Object} dept   部门对象
       * @param {Number} status 最新状态
       */
      updateDeptStatusHandle(dept, status) {
        // 按钮不可被点击
        this.buttonLoad = true;
        this.$axios.$post('/sys/dept/update/status', { deptId: dept.deptId, status: status })
          .then(() => {
            // 变更部门状态
            dept.status = status;
          })
          .catch(() => {})
          .finally(() => {
            // 按钮恢复可点击
            this.buttonLoad = false;
          })
      },
      /**
       * 删除部门数据事件
       * @param {Object} dept 部门数据对象
       */
      deleteDeptBeforeHandle (dept) {
        // 按钮不可被点击
        this.buttonLoad = true;
        this.$axios.$get('/sys/dept/delete/check', { params: { deptId: dept.deptId }})
          .then(({ data }) => {
            this.$nextTick(() => {
              this.$refs.deptDeleteConfirmDialog.initDeptDeleteConfirmDialog(dept, data);
            })
          })
          .catch(() => {})
          .finally(() => {
            // 按钮恢复可点击
            this.buttonLoad = false;
          })
      },
      /**
       * 打开系统部门操作弹出框事件
       * @param {Object}  dept    系统部门对象
       * @param {boolean} optType 系统部门操作类型[false-添加 true-修改]
       */
      openDeptDialogHandle(dept, optType) {
        this.$refs.optDeptDialog.initDeptDialog(dept, optType)
      },
      /**
       * 关闭系统部门操作弹出框事件
       * @param {boolean} bool true-刷新表格数据 false-不刷新表格数据
       */
      closeDeptDialogHandle(bool) {
        if (bool) {
          // 请求模式置0，下一次请求会重新获取数据
          this.requestMode = 0;

          this.getDeptList()
        }
      },
      /**
       * 关闭部门删除提示弹出框事件
       * @param {boolean} bool true-刷新表格数据 false-不刷新表格数据
       */
      closeDeptDeleteDialogHandle(bool) {
        if (bool) {
          // 请求模式置0，下一次请求会重新获取数据
          this.requestMode = 0;

          this.getDeptList()
        }
      },
      /**
       * 跳转到部门与用户页面
       * @param dept 部门数据对象
       */
      toDeptUserPageHandle(dept) {
        this.$router.push({ path: '/admin/system/dept-user', query: { dept: dept.deptId, deptName: dept.deptName }})
      },
      /**
       * 跳转到部门与角色页面
       * @param {Object} dept 部门对象
       */
      toDeptRolePageHandle(dept) {
        this.$router.push({ path: '/admin/system/dept-role', query: { dept: dept.deptId, deptName: dept.deptName }})
      }
    }
  }
</script>

<style scoped>
  .dept-page .d-tool {
    margin-bottom: 7px;
  }
  .dept-page .dropdown-opt {
    font-size: 12px;
    margin-left: 7px;
    --color: black;
    color: var(--color);
  }
  .dept-page .paging {
    float: right;
    margin: 7px;
  }
</style>
